(function(){
  function activate(hash){
    var target = document.querySelector(hash);
    if(!target) return;
    document.querySelectorAll('main .section').forEach(function(sec){
      var isTarget = '#' + sec.id === hash;
      if(isTarget){ sec.removeAttribute('hidden'); sec.classList.add('active'); }
      else { sec.setAttribute('hidden',''); sec.classList.remove('active'); }
    });
    // 高亮 tab
    document.querySelectorAll('.tabs .tab[data-target]').forEach(function(btn){
      var on = btn.getAttribute('data-target') === hash;
      btn.setAttribute('aria-selected', on ? 'true' : 'false');
      if(on) btn.classList.add('active'); else btn.classList.remove('active');
    });
    // 滚动到内容区域
    try{ if(hash !== '#invoice' && hash !== '#favorites'){ /* prevent auto-scroll on 收藏 */ target.scrollIntoView({behavior:'smooth', block:'start'}); } }catch(_){}
  }

  // click 事件
  document.addEventListener('click', function(e){
    var btn = e.target.closest('.tabs .tab[data-target]');
    if(!btn) return;
    var hash = btn.getAttribute('data-target');
    if(hash){ e.preventDefault(); activate(hash); history.replaceState(null,'',hash); }
  });

  // 初始态：按 URL hash 激活；无 hash 则保持默认（#overview）
  document.addEventListener('DOMContentLoaded', function(){
    var hash = location.hash && document.querySelector(location.hash) ? location.hash : null;
    if(hash){ activate(hash); }
  });
})();